import SwiftUI

struct ProfileView: View {
    @StateObject var viewModel = ProfileViewModel()
    @State private var showingResetAlert = false
    @State private var showingSavedAlert = false
    @State private var selectedTab = 0
    
    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                // 顶部用户信息卡片
                UserProfileCard(
                    name: viewModel.userProfile.name.isEmpty ? "未设置姓名" : viewModel.userProfile.name,
                    level: viewModel.calculateUserLevel(),
                    points: viewModel.achievementPoints,
                    streakDays: viewModel.streakDays
                )
                .padding()
                
                // 选项卡切换
                Picker("", selection: $selectedTab) {
                    Text("个人信息").tag(0)
                    Text("成就").tag(1)
                    Text("健康指标").tag(2)
                }
                .pickerStyle(SegmentedPickerStyle())
                .padding(.horizontal)
                
                TabView(selection: $selectedTab) {
                    // 个人信息标签
                    personalInfoTab
                        .tag(0)
                    
                    // 成就标签
                    achievementsTab
                        .tag(1)
                    
                    // 健康指标标签
                    healthMetricsTab
                        .tag(2)
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
            }
            .navigationTitle("个人中心")
            .navigationBarTitleDisplayMode(.inline)
            .alert("信息已保存", isPresented: $showingSavedAlert) {
                Button("确定", role: .cancel) { }
            } message: {
                Text("你的个人信息已成功保存")
            }
            .alert("重置数据", isPresented: $showingResetAlert) {
                Button("取消", role: .cancel) { }
                Button("确认重置", role: .destructive) {
                    viewModel.resetUserData()
                }
            } message: {
                Text("这将清除所有个人数据和饮水记录，确定要继续吗？")
            }
        }
    }
    
    // 个人信息标签页
    var personalInfoTab: some View {
        Form {
            // 个人信息
            Section(header: Text("个人信息")) {
                TextField("姓名", text: $viewModel.userProfile.name)
                
                HStack {
                    Text("体重")
                    Spacer()
                    TextField("公斤", value: $viewModel.userProfile.weight, format: .number)
                        .keyboardType(.decimalPad)
                        .multilineTextAlignment(.trailing)
                    Text("kg")
                }
                
                // 性别选择
                Picker("性别", selection: $viewModel.gender) {
                    Text("男").tag("male")
                    Text("女").tag("female")
                    Text("其他").tag("other")
                }
                
                // 年龄输入
                HStack {
                    Text("年龄")
                    Spacer()
                    TextField("岁", value: $viewModel.age, format: .number)
                        .keyboardType(.numberPad)
                        .multilineTextAlignment(.trailing)
                    Text("岁")
                }
                
                Button("计算推荐饮水量") {
                    let recommended = viewModel.calculateRecommendedGoal()
                    viewModel.userProfile.goal = recommended
                }
                .foregroundColor(.blue)
            }
            
            // HealthKit集成
            Section(header: Text("健康数据")) {
                Toggle("与健康App同步", isOn: $viewModel.isHealthKitEnabled)
                    .onChange(of: viewModel.isHealthKitEnabled) { newValue in
                        viewModel.toggleHealthKitIntegration(isEnabled: newValue)
                    }
                
                if viewModel.isHealthKitEnabled {
                    Text("饮水数据将自动与健康App同步")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            
            // 保存和重置按钮
            Section {
                Button("保存信息") {
                    viewModel.saveUserProfile(
                        name: viewModel.userProfile.name,
                        weight: viewModel.userProfile.weight
                    )
                    showingSavedAlert = true
                }
                .frame(maxWidth: .infinity, alignment: .center)
                .foregroundColor(.blue)
                
                Button("重置所有数据") {
                    showingResetAlert = true
                }
                .frame(maxWidth: .infinity, alignment: .center)
                .foregroundColor(.red)
            }
        }
    }
    
    // 成就标签页
    var achievementsTab: some View {
        ScrollView {
            VStack(spacing: 20) {
                // 用户总成就统计
                HStack(spacing: 30) {
                    StatCard(title: "总成就", value: "\(viewModel.unlockedAchievements.count)/\(viewModel.totalAchievements)")
                    StatCard(title: "连续达标", value: "\(viewModel.streakDays)天")
                }
                .padding(.horizontal)
                .padding(.top)
                
                // 成就列表
                VStack(alignment: .leading) {
                    Text("我的成就")
                        .font(.headline)
                        .padding(.horizontal)
                    
                    ForEach(viewModel.achievements, id: \.title) { achievement in
                        AchievementRow(
                            title: achievement.title,
                            description: achievement.description,
                            isUnlocked: viewModel.unlockedAchievements.contains(achievement.title),
                            progress: achievement.progress
                        )
                        .padding(.vertical, 8)
                        .padding(.horizontal)
                        .background(Color(.systemGray6).opacity(0.5))
                        .cornerRadius(10)
                        .padding(.horizontal)
                    }
                }
                .padding(.bottom)
            }
        }
    }
    
    // 健康指标标签页
    var healthMetricsTab: some View {
        Form {
            Section(header: Text("身体指标")) {
                // 身高输入
                HStack {
                    Text("身高")
                    Spacer()
                    TextField("厘米", value: $viewModel.height, format: .number)
                        .keyboardType(.decimalPad)
                        .multilineTextAlignment(.trailing)
                    Text("cm")
                }
                
                // BMI计算
                HStack {
                    Text("BMI指数")
                    Spacer()
                    Text(String(format: "%.1f", viewModel.calculateBMI()))
                        .fontWeight(.bold)
                    
                    // BMI状态指示器
                    Text(viewModel.getBMIStatus())
                        .foregroundColor(viewModel.getBMIStatusColor())
                        .font(.caption)
                        .padding(.horizontal, 8)
                        .padding(.vertical, 4)
                        .background(viewModel.getBMIStatusColor().opacity(0.2))
                        .cornerRadius(8)
                }
            }
            
            Section(header: Text("饮水习惯")) {
                // 平均每日饮水量
                HStack {
                    Text("平均每日饮水量")
                    Spacer()
                    Text("\(Int(viewModel.averageDailyIntake))毫升")
                        .fontWeight(.medium)
                }
                
                // 达标率
                HStack {
                    Text("目标达成率")
                    Spacer()
                    Text(String(format: "%.0f%%", viewModel.goalAchievementRate * 100))
                        .fontWeight(.medium)
                }
                
                // 饮水时间分布图
                VStack(alignment: .leading, spacing: 10) {
                    Text("饮水时间分布")
                        .font(.subheadline)
                    
                    IntakeDayDistributionBar(distribution: viewModel.getIntakeDistribution())
                        .frame(height: 40)
                }
                .padding(.vertical, 8)
            }
            
            Section(header: Text("健康建议")) {
                ForEach(viewModel.getHealthSuggestions(), id: \.self) { suggestion in
                    HStack(spacing: 12) {
                        Image(systemName: "lightbulb.fill")
                            .foregroundColor(.yellow)
                        
                        Text(suggestion)
                            .font(.subheadline)
                    }
                    .padding(.vertical, 4)
                }
            }
        }
    }
}

// 用户个人资料卡片
struct UserProfileCard: View {
    var name: String
    var level: Int
    var points: Int
    var streakDays: Int
    
    var body: some View {
        VStack(spacing: 15) {
            // 用户头像
            ZStack {
                Circle()
                    .fill(Color.blue.opacity(0.1))
                    .frame(width: 90, height: 90)
                
                Text(String(name.prefix(1)))
                    .font(.system(size: 36, weight: .bold))
                    .foregroundColor(.blue)
            }
            
            // 用户名称和等级
            VStack(spacing: 5) {
                Text(name)
                    .font(.title2)
                    .fontWeight(.bold)
                
                HStack {
                    Image(systemName: "star.fill")
                        .foregroundColor(.yellow)
                    Text("等级 \(level)")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                }
            }
            
            // 用户数据
            HStack(spacing: 30) {
                VStack {
                    Text("\(points)")
                        .font(.headline)
                    Text("成就点数")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                
                Divider()
                    .frame(height: 30)
                
                VStack {
                    Text("\(streakDays)")
                        .font(.headline)
                    Text("连续天数")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            .padding(.top, 5)
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(15)
    }
}

// 成就行
struct AchievementRow: View {
    var title: String
    var description: String
    var isUnlocked: Bool
    var progress: Double
    
    var body: some View {
        HStack {
            // 成就图标
            ZStack {
                Circle()
                    .fill(isUnlocked ? Color.blue : Color.gray.opacity(0.3))
                    .frame(width: 44, height: 44)
                
                Image(systemName: isUnlocked ? "trophy.fill" : "lock.fill")
                    .foregroundColor(isUnlocked ? .white : .gray)
            }
            
            // 成就信息
            VStack(alignment: .leading, spacing: 5) {
                Text(title)
                    .font(.headline)
                
                Text(description)
                    .font(.caption)
                    .foregroundColor(.secondary)
                
                // 进度条
                if !isUnlocked && progress > 0 {
                    VStack(alignment: .leading, spacing: 2) {
                        ProgressView(value: progress)
                            .progressViewStyle(LinearProgressViewStyle(tint: .blue))
                            .frame(height: 8)
                        
                        Text("\(Int(progress * 100))%")
                            .font(.caption2)
                            .foregroundColor(.secondary)
                    }
                }
            }
            
            Spacer()
            
            // 解锁状态
            if isUnlocked {
                Image(systemName: "checkmark.circle.fill")
                    .foregroundColor(.green)
            }
        }
    }
}

// 统计数据卡片
struct StatCard: View {
    var title: String
    var value: String
    
    var body: some View {
        VStack(spacing: 5) {
            Text(title)
                .font(.caption)
                .foregroundColor(.secondary)
            
            Text(value)
                .font(.title3)
                .fontWeight(.bold)
        }
        .frame(maxWidth: .infinity)
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(10)
    }
}

// 饮水时间分布条形图
struct IntakeDayDistributionBar: View {
    var distribution: [Double]
    
    var body: some View {
        GeometryReader { geometry in
            HStack(spacing: 2) {
                ForEach(0..<distribution.count, id: \.self) { index in
                    let value = distribution[index]
                    let maxValue = distribution.max() ?? 1.0
                    let height = geometry.size.height * (value / maxValue)
                    
                    VStack {
                        Spacer()
                        
                        Rectangle()
                            .fill(colorForHour(index))
                            .frame(height: height)
                            .cornerRadius(2)
                    }
                }
            }
        }
    }
    
    // 根据时间段返回不同颜色
    private func colorForHour(_ hour: Int) -> Color {
        let normalizedHour = hour / 2 // 将24小时分成12个时段
        
        switch normalizedHour {
        case 0...2: // 0-6点，深夜
            return Color.purple.opacity(0.7)
        case 3...4: // 6-10点，早晨
            return Color.orange
        case 5...7: // 10-16点，中午和下午
            return Color.blue
        case 8...9: // 16-20点，傍晚
            return Color.green
        case 10...11: // 20-24点，晚上
            return Color.indigo.opacity(0.7)
        default:
            return Color.gray
        }
    }
} 